#include "polygonpointsmodel.h"

PolygonPointsModel::PolygonPointsModel(AED_PhysicsComp *comp, QObject *parent) :
    QAbstractTableModel(parent),m_comp(comp)
{
    m_list = comp->GetPoints();
}

int PolygonPointsModel::rowCount(const QModelIndex & parent) const{
    return m_list->size();
}

int PolygonPointsModel::columnCount(const QModelIndex & parent) const{
    return 2;
}

QVariant PolygonPointsModel::data ( const QModelIndex & index, int role) const{
    if(role==Qt::DisplayRole||role==Qt::EditRole){
        int row = index.row();

        AED_PhysicsComp::Point point = (*m_list)[row];


        QVariant var;

        if(index.column()==0)
            var = point.x;
        else if(index.column()==1)
            var = point.y;
        else
            return QVariant(QVariant::Invalid);
        return var;
    }
    return QVariant(QVariant::Invalid);
}

QVariant PolygonPointsModel::headerData ( int section, Qt::Orientation orientation, int role) const{
    if(orientation==Qt::Horizontal){
        if (role==Qt::DisplayRole||role==Qt::EditRole){
            if(section==0)
                return tr("X");
            else if(section==1)
                return tr("Y");
        }else{
            return QVariant(QVariant::Invalid);
        }
    }else{
        if (role==Qt::DisplayRole||role==Qt::EditRole){
            QVariant h(QVariant::Int);
            h=section+1;
            return h;
        }else{
            return QVariant(QVariant::Invalid);
        }
    }
    return QVariant(QVariant::Invalid);
}

void PolygonPointsModel::AddPoint(){
    m_comp->AddPoint(0,0);

    emit layoutChanged();
}

void PolygonPointsModel::RemovePoint(int index){
    m_comp->RemovePoint(index);
    emit layoutChanged();
}

bool PolygonPointsModel::setData(const QModelIndex &index, const QVariant &value, int role){
    int row = index.row();
    int column = index.column();

    if(index.isValid() && role==Qt::EditRole){
        if(column==0){
            (*m_list)[row].x = value.toFloat();
        }else if(column==1){
            (*m_list)[row].y = value.toFloat();
        }else{
            return false;
        }
        emit dataChanged(index,index);
        return true;
    }

    return false;
}

Qt::ItemFlags PolygonPointsModel::flags(const QModelIndex &index) const{
    Qt::ItemFlags flags = Qt::ItemIsEnabled|Qt::ItemIsEditable|Qt::ItemIsSelectable;
    return flags;
}


